package com.example.music_project.controller;

import com.example.music_project.tools.Result;
import com.example.music_project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.SimpleTimeZone;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
     BCryptPasswordEncoder bCryptPasswordEncoder;
    @Value("${music.local.path}")
    public String filePath;
    //登录
    @RequestMapping("/login")
    public Result<Object> login(String userName, String password, HttpServletRequest request) {
        log.info("userName:{}", userName);
        log.info("password:{}", password);
        return userService.queryUser(userName, password, request);
    }

    //注册
    @RequestMapping("/signIn")
    public Result<Object> signIn(String userName, String password) {
        Result<Object> result = new Result<>();
        // 1.校验
        log.info("userName:{}", userName);
        log.info("password:{}", password);
        if(!userService.register(userName, password)) {
            return result.fail("用户名或密码为空");
        }
        return result.success();
    }

   @RequestMapping("/upload")
    public void upload(MultipartFile file) throws IOException, UnsupportedAudioFileException {
       String originalFilename = file.getOriginalFilename();// ***.mp3
       String path = filePath + originalFilename;
       System.out.println("paht" + path);
       File dest = new File(path);
       if(!dest.exists()) {
           dest.mkdirs();
       }
       file.transferTo(dest);
       //将文件转换为MP3格式

//       byte[] bytes = file.getBytes();
//       int bytesLen = bytes.length;
//       System.out.println("bytesLen"+bytesLen);
//       int flag = bytesLen - 128-3;
//       System.out.println(flag);
//       byte[] bytes2 = Arrays.copyOfRange(bytes, flag, bytesLen);
//       String s = new String(bytes2);
//
//       System.out.println("s:" + s);
//       System.out.println("bytes2:" + bytes2.length);
//       byte[] b = new byte[3];
//       for(int i = 0; i < 3; i++) {
//           b[i] = bytes2[i];
//       }
//       System.out.println(new String(b));
   }
}
